package com.lanou.dllo.baisibudejie.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanou.dllo.baisibudejie.qqLogin.Util;
import com.lanou.dllo.baisibudejie.activity.InstalledActivity;
import com.lanou.dllo.baisibudejie.activity.LoginActivity;
import com.lanou.dllo.baisibudejie.R;
import com.lanou.dllo.baisibudejie.activity.WebActivity;
import com.lanou.dllo.baisibudejie.volley.DiskCache;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by dllo on 15/10/22.
 */
public class MyFragment extends Fragment implements View.OnClickListener {

    private TextView my_loginTv, downloadTv, webViewTv, user_nickname;
    private ImageView myinfo_settingIv, user_logo;
    private boolean isLogin;
    private LinearLayout myLinear;
    private boolean qqLogin = false;
    private boolean isExit;


    private static final String TAG = LoginActivity.class.getName();
    public static String mAppid;
    public static QQAuth mQQAuth;
    private UserInfo mInfo;
    private Tencent mTencent;
    private final String APP_ID = "222222";// 测试时使用，真正发布的时候要换成自己的APP_ID
    private String name;
    private Bitmap bitmap = null;
    private String login_name;

    public MyFragment(boolean isExit) {
        super();
        this.isExit = isExit;

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }


    /**
     * 在这个方法里面，获取传入的数据
     *
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onStart() {
        final Context context = getActivity();
        final Context ctxContext = context.getApplicationContext();
        mAppid = APP_ID;
        mQQAuth = QQAuth.createInstance(mAppid, ctxContext);
        mTencent = Tencent.createInstance(mAppid, getActivity());
        super.onStart();
    }

    /**
     * 这个方法里面加载布局
     */
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, null);

        return view;
    }


    /**
     * 控件初始化在这写
     */
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        my_loginTv = (TextView) view.findViewById(R.id.my_loginTv);//登录/注册
        my_loginTv.setOnClickListener(this);
        my_loginTv.setVisibility(View.VISIBLE);
        myinfo_settingIv = (ImageView) view.findViewById(R.id.myinfo_settingIv);//设置
        myinfo_settingIv.setOnClickListener(this);
        downloadTv = (TextView) view.findViewById(R.id.downloadTv);//离线下载
        downloadTv.setOnClickListener(this);
        myLinear = (LinearLayout) view.findViewById(R.id.myLinear);
        webViewTv = (TextView) view.findViewById(R.id.webViewTv);//网页
        webViewTv.setOnClickListener(this);
        user_logo = (ImageView) view.findViewById(R.id.my_user_logo);//头像
        user_logo.setVisibility(View.GONE);
        user_nickname = (TextView) view.findViewById(R.id.my_user_nickname);//昵称
//        user_nickname.setVisibility(View.GONE);


        if (!isExit) {//判断是否退出
            my_loginTv.setVisibility(View.GONE);
            user_nickname.setVisibility(View.VISIBLE);
            user_logo.setVisibility(View.VISIBLE);
        } else {
            my_loginTv.setVisibility(View.VISIBLE);
            user_nickname.setVisibility(View.GONE);
            user_logo.setVisibility(View.GONE);
        }

    }


    /**
     * 数据初始化在这写
     *
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (login_name != null) {//判断是否传来昵称
            user_nickname.setText("暂无昵称");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_loginTv://登录／注册
                Intent intent_login = new Intent(getActivity(), LoginActivity.class);

                startActivityForResult(intent_login, 400);
                break;
            case R.id.myinfo_settingIv://设置
                Intent intent_setting = new Intent(getActivity(), InstalledActivity.class);
                intent_setting.putExtra("isLogin", isLogin);
                intent_setting.putExtra("qqLogin", qqLogin);
                intent_setting.putExtra("isExit", isExit);
                startActivityForResult(intent_setting, 500);
                break;
            case R.id.downloadTv://离线下载

                break;
            case R.id.webViewTv:
                Intent intent_web = new Intent(getActivity(), WebActivity.class);
                startActivity(intent_web);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        if (resultCode == 500 && requestCode == 500) {
            isLogin = data.getBooleanExtra("isLogin", false);
            qqLogin = data.getBooleanExtra("qqLogin", false);
            isExit = data.getBooleanExtra("isExit", true);
            if (!isLogin || !qqLogin) {
                transaction.replace(R.id.tabcontent_news, new NewsFragment());
                transaction.replace(R.id.tabcontent_my, new MyFragment(true));

            }
            if (qqLogin && isExit) {
                QQLogin();
            }


        }
        if (resultCode == 400 && requestCode == 400) {
            isLogin = data.getBooleanExtra("isLogin", false);
            isExit = data.getBooleanExtra("isExit", true);
            login_name = data.getStringExtra("login_name");
            Log.i("lanou00",login_name+"jjj" );

            user_nickname.setText(login_name );
            user_nickname.setVisibility(View.VISIBLE);

            if (isLogin) {

                transaction.replace(R.id.tabcontent_news, new MyNewsFragment());//替换页面
                transaction.replace(R.id.tabcontent_my, new MyFragment(false));
            }
        }
        if (resultCode == 200 && requestCode == 400) {
            qqLogin = data.getBooleanExtra("qqLogin", false);
            isExit = data.getBooleanExtra("isExit", true);
            if (qqLogin) {
                QQLogin();

                transaction.replace(R.id.tabcontent_news, new MyNewsFragment());//替换页面

            }
        }
        transaction.commit();
    }

    private void QQLogin() {
        my_loginTv.setVisibility(View.GONE);

        onClickLogin();
        user_nickname.setVisibility(View.VISIBLE);
        user_logo.setVisibility(View.VISIBLE);

    }

    private void onClickLogin() {
        if (!mQQAuth.isSessionValid()) {
            IUiListener listener = new BaseUiListener() {
                @Override
                protected void doComplete(JSONObject values) {
                    updateUserInfo();
                }
            };
            mQQAuth.login(getActivity(), "all", listener);
            // mTencent.loginWithOEM(this, "all",
            // listener,"10000144","10000144","xxxx");
            mTencent.login(getActivity(), "all", listener);
        } else {
            mQQAuth.logout(getActivity());
            updateUserInfo();
        }
    }

    private void updateUserInfo() {
        if (mQQAuth != null && mQQAuth.isSessionValid()) {
            IUiListener listener = new IUiListener() {

                public void onError(UiError e) {
                    // TODO Auto-generated method stub

                }


                public void onComplete(final Object response) {
                    Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                    new Thread() {

                        @Override
                        public void run() {
                            JSONObject json = (JSONObject) response;
                            if (json.has("figureurl")) {
                                Bitmap bitmap = null;
                                try {
                                    bitmap = Util.getbitmap(json
                                            .getString("figureurl_qq_2"));
                                } catch (JSONException e) {

                                }
                                Message msg = new Message();
                                msg.obj = bitmap;
                                msg.what = 1;
                                mHandler.sendMessage(msg);
                            }
                        }

                    }.start();
                }


                public void onCancel() {
                }
            };
            mInfo = new UserInfo(getActivity(), mQQAuth.getQQToken());
            mInfo.getUserInfo(listener);

        } else {
            user_nickname.setText("");
            user_nickname.setVisibility(android.view.View.GONE);
            user_logo.setVisibility(android.view.View.GONE);
        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = (JSONObject) msg.obj;
                if (response.has("nickname")) {
                    try {
                        user_nickname.setVisibility(android.view.View.VISIBLE);
                        user_nickname.setText(response.getString("nickname"));
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else if (msg.what == 1) {
                Bitmap bitmap = (Bitmap) msg.obj;
                DiskCache cache = new DiskCache();
                cache.putBitmap("abcd", bitmap);
                user_logo.setImageBitmap(bitmap);
                user_logo.setVisibility(android.view.View.VISIBLE);
            }
        }

    };

    private class BaseUiListener implements IUiListener {


        public void onComplete(Object response) {
//            Util.showResultDialog(getActivity(), response.toString(),
//                    "登录成功");
            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {

        }


        public void onError(UiError e) {
            Util.toastMessage(getActivity(), "onError: " + e.errorDetail);
            Util.dismissDialog();
        }

        public void onCancel() {
            Util.toastMessage(getActivity(), "onCancel: ");
            Util.dismissDialog();
        }
    }

    public final Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;

        try {
            myFileUrl = new URL(url);
            HttpURLConnection conn;

            conn = (HttpURLConnection) myFileUrl.openConnection();

            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }
}
